<template>
	<view class="container">
		<uni-file-picker ref="filePicker" v-model="fileList" :auto-upload="false" file-mediatype="image" mode="grid"
			limit="5" @select="onSelect" @delete="onDelete">
			<button type="primary">选择文件</button>
		</uni-file-picker>

		<button class="upload-button" type="primary" :disabled="uploading || !hasFiles" @click="startUpload">
			{{ uploading ? `上传中...${uploadProgress}%` : '开始上传' }}
		</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				fileList: [],
				uploading: false,
				uploadProgress: 0,
				uploadTasks: [] // 存储上传任务
			}
		},
		computed: {
			hasFiles() {
				return this.fileList.length > 0;
			}
		},
		methods: {
			onSelect(selectFiles) {
				// 初始化文件状态
				this.fileList = [...this.fileList, ...selectFiles.tempFiles.map(file => ({
					...file,
					status: 'ready',
					progress: 0
				}))];
			},

			// 生成唯一文件名
			generateCloudPath(originalName) {
				const ext = originalName.split('.').pop();
				const timestamp = Date.now();
				const date = uni.$dayjs(timestamp).format('YYYY-MM-DD')
				const mobile = uni.getStorageSync('userInfo').mobile
				return `fuel/${mobile}/${date}/${timestamp}.${ext}`;
			},

			async startUpload() {
				if (this.fileList.length === 0) {
					uni.showToast({
						title: '请先选择文件',
						icon: 'none'
					});
					return;
				}

				this.uploading = true;
				this.uploadProgress = 0;
				this.uploadTasks = [];

				// 重置所有文件状态
				this.fileList = this.fileList.map(file => ({
					...file,
					status: 'uploading',
					progress: 0
				}));

				// 创建所有上传任务
				for (const file of this.fileList) {
					if (file.status === 'success') continue;

					const task = this.uploadFile(file);
					this.uploadTasks.push(task);
				}

				// 等待所有任务完成
				try {
					await Promise.all(this.uploadTasks);
					uni.showToast({
						title: '全部文件上传完成',
						icon: 'success'
					});
				} catch (e) {
					console.error('上传出错', e);
				} finally {
					this.uploading = false;
				}
			},

			// 单个文件上传
			uploadFile(file) {
				return new Promise((resolve, reject) => {
					const cloudPath = this.generateCloudPath(file.name);

					const uploadTask = uniCloud.uploadFile({
						filePath: file.path,
						cloudPath: cloudPath,
						cloudPathAsRealPath: true, // 使用真实路径
						onUploadProgress: (progressEvent) => {
							// 更新单个文件进度
							const progress = Math.round(
								(progressEvent.loaded / progressEvent.total) * 100
							);

							this.updateFileProgress(file.uuid, progress);

							// 计算整体进度
							this.calculateTotalProgress();
						},
						success: (res) => {
							this.updateFileStatus(file.uuid, 'success');
							console.log('上传成功', res.fileID);
							resolve(res);
						},
						fail: (err) => {
							console.error('上传失败', err);
							this.updateFileStatus(file.uuid, 'fail');
							reject(err);
						}
					});
				});
			},

			// 更新文件进度
			updateFileProgress(uuid, progress) {
				this.fileList = this.fileList.map(file => {
					if (file.uuid === uuid) {
						return {
							...file,
							progress: progress
						};
					}
					return file;
				});
			},

			// 更新文件状态
			updateFileStatus(uuid, status) {
				this.fileList = this.fileList.map(file => {
					if (file.uuid === uuid) {
						return {
							...file,
							status: status
						};
					}
					return file;
				});
			},

			// 计算整体进度
			calculateTotalProgress() {
				if (this.fileList.length === 0) return;

				const totalProgress = this.fileList.reduce((sum, file) => {
					return sum + (file.progress || 0);
				}, 0);

				this.uploadProgress = Math.round(totalProgress / this.fileList.length);
			},

			onDelete(file) {
				this.fileList = this.fileList.filter(f => f.uuid !== file.uuid);

				// 如果删除的是正在上传的文件
				if (file.status === 'uploading') {
					this.calculateTotalProgress();
				}
			}
		}
	}
</script>

<style>
	.container {
		padding: 20px;
	}

	.upload-button {
		margin-top: 20px;
		width: 100%;
	}

	button[disabled] {
		opacity: 0.6;
		background-color: #ccc !important;
	}
</style>